package com.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.web.servlet.bean.GameInfo;
import com.web.servlet.bean.GameServerInfo;
import com.web.servlet.bean.RedisKey;
import com.web.servlet.bean.UserInfo;
import com.web.servlet.manager.GameServerMananger;
import com.web.servlet.manager.RedisManager;
/**
 * 获得 连接的游戏服务器 信息
 * @author davie.yu
 *
 */
public class GameServerInfoServlet extends HttpServlet {

	private static final long serialVersionUID = -3425439168209857070L;
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		response.setContentType("text/plain");
		response.setCharacterEncoding("utf-8");
		
		PrintWriter out = response.getWriter();
		
		int  gameId = Integer.valueOf(request.getParameter("gameId"));//游戏ID信息
		int userid  = Integer.valueOf(request.getParameter("userId"));//用户ID
		//游戏列表
		GameInfo info  = GameServerMananger.getGameInfoByID(gameId);
		if(null == info ){//判断游戏是否存在
			return;
		}
		if(2 == info.getGame_status()){//判断游戏状态 是否 开放
			return;
		}
		//redis 保存 token 数据
		String value = RedisManager.getRedis().get(RedisKey.USERINFO+userid);
		if(null == value){
			return;
		}
		UserInfo userinfo = UserInfo.parse(value);
		userinfo.token = "token";
		RedisManager.getRedis().set(RedisKey.USERINFO+userid, userinfo.pack());
		
		
		GameServerInfo  gameServerInfo =  GameServerMananger.getGameServerInfoByID(gameId);
		Document document = DocumentHelper.createDocument();
    	Element rootElement = document.addElement("GameServerInfo");
    	if(null != gameServerInfo){
			rootElement.addAttribute("id", String.valueOf(gameServerInfo.getGame_id()));//gameID
			rootElement.addAttribute("url", gameServerInfo.getGame_url());//Ip和端口
			rootElement.addAttribute("t", "token");
	    	out.print(document.asXML());
			out.flush();
			out.close();
		}
		out.flush();
		out.close();
	}


}
